//
//  ST_ConversionConfirmViewController.swift
//  btvideo
//
//  Created by mac on 2020/10/12.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyAttributes
import SweeterSwift
import SwiftyUserDefaults
import RxCocoa
import RxSwift
import SwiftyJSON
import KeychainAccess


class ST_ConversionConfirmViewController: UIViewController {
    
    let data:ST_ConversionGoodsModel
    
    init(data:ST_ConversionGoodsModel){
        self.data = data
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

    var disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .clear
        
        let h = 15+BTSafeAreaBottom + (self.data.type != 2 ? 243 : 320)
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(15)
            make.height.equalTo(h)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(left_label)
        left_label.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(15)
            make.height.equalTo(22)
        }
        
        
        root_view.addSubview(cash_subscribe_label)
        cash_subscribe_label.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_label)
            make.right.equalToSuperview().offset(-15)
        }
        
        root_view.addSubview(goods_label)
        goods_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(left_label.snp.bottom).offset(26)
            make.height.equalTo(22)
        }
        
        root_view.addSubview(goods_name_label)
        goods_name_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(goods_label.snp.bottom).offset(20)
            make.height.equalTo(36)
        }
        
        
        
        root_view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.width.equalTo(345)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-15-BTSafeAreaBottom-15)
        }
        
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo{
            self.create_cash_label_value(value: user.income)
        }else{
            self.create_cash_label_value(value: 0)
        }
        
        
        layout_steps_view()
        
        binding()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if data.type == 2{
            confirm_btn.loading()
            fetchStatus()
        }else{
            status_observable.accept(.finished)
        }
    }
    
    fileprivate func layout_steps_view(){
        
        if self.data.type != 2{
            return
        }
        
        step_views.forEach({ root_view.addSubview($0) })
        
        step_line_views.forEach({ root_view.addSubview($0) })
        
        stepView1.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            
            make.top.equalTo(goods_name_label.snp.bottom).offset(30)
            make.height.equalTo(18+11+28)
            make.width.equalTo(78)
        }
        
        stepView4.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.width.height.equalTo(stepView1)
        }
        
        stepView2.snp.makeConstraints { (make) in
            make.right.equalTo(root_view.snp.centerX).offset(-10)
            make.top.width.height.equalTo(stepView1)
        }
        
        
        stepView3.snp.makeConstraints { (make) in
            make.left.equalTo(root_view.snp.centerX).offset(10)
            make.top.width.height.equalTo(stepView1)
        }
        
        
        let lineOffset = 25
        
        stepLine1.snp.makeConstraints { make in
            make.height.equalTo(2)
            make.top.equalTo(stepView1).offset(28/2-1)
            make.left.equalTo(stepView1.snp.right).offset(-lineOffset)
            make.right.equalTo(stepView2.snp.left).offset(lineOffset)
        }
        
        stepLine2.snp.makeConstraints { make in
            make.height.top.equalTo(stepLine1)
            make.left.equalTo(stepView2.snp.right).offset(-lineOffset)
            make.right.equalTo(stepView3.snp.left).offset(lineOffset)
        }
        
        stepLine3.snp.makeConstraints { make in
            make.height.top.equalTo(stepLine1)
            make.left.equalTo(stepView3.snp.right).offset(-lineOffset)
            make.right.equalTo(stepView4.snp.left).offset(lineOffset)
        }
        
    }
    
    fileprivate var status_observable = BehaviorRelay<ZLBStatus?>(value: nil)
    
    fileprivate func fetchStatus(){
        
        TIANSession(requestUrl: PH.fetchStatusOFZLBApi).concatMap { result -> Observable<ZLBStatus> in
            
            switch result {
            case .success(let json):
                
                let stepValue = json["data"]["auth_status"].intValue
                
                switch stepValue {
                case 1633942749:
                  
                    return TIANSession(requestUrl: PH.registZLBApi).flatMapLatest { res0 -> Observable<Result<JSON,ST_NetworkError>> in
                        switch res0 {
                        case .success:
                            return TIANSession(requestUrl: PH.getZLBH5URLApi)
                        case .failure:
                            print("注册方法报错了")
                            return Observable.just(res0)
                        }
                    }.map({ $0.covertToZLBStatus(step: 1) })

                case 4:
                    return Observable.just(ZLBStatus.finished)
                default:
                    return TIANSession(requestUrl: PH.getZLBH5URLApi).map({ $0.covertToZLBStatus(step: stepValue) })
                }
                
            case .failure(let err):

                return Observable.just(ZLBStatus.error(e: err))
            }
        }.bind(to: self.status_observable).disposed(by: disposeBag)
        
    }
    
    fileprivate func binding(){
        
        goods_name_label.text = data.name
        
        status_observable.subscribe(onNext: {[weak self] _ in
            self?.status_updated()
        }).disposed(by: disposeBag)
       
        
        confirm_btn.rx.controlEvent(.touchUpInside).withUnretained(self).subscribe(onNext: { own,_ in
            
            if FACE_AVATAE_STATE != 3 && own.data.type == 2{
                own.push_detect_face()
                return
            }
            
            guard let element0 =  own.status_observable.value else {
                return
            }
            
            switch element0 {
                
            case .ongoing(_,let link):
                
                let vc = ST_BTWebViewController()
                
                vc.urlStr = link.absoluteString
                
                own.navigationController?.pushViewController(vc, animated: true)
                
            case .finished:
                
                own.exchange_action()
                
            case .error(let err):
                own.toast(text: err.e)
            }
            
        }).disposed(by: disposeBag)
        
        
        
        
    }
    
    fileprivate func exchange_action(){
        
        
        
        self.confirm_btn.loading()
        
        TIANSession(requestUrl: PH.exchangeByIncomeApi, parameters: ["mall_id":self.data.id]).subscribe(onNext: {[weak self] result in
            
            self?.confirm_btn.loading(status: false)
            
            switch result {
                
            case .failure(let error):
                if error.code == 10003{
                    self?.push_detect_face()
                }else{
                    self?.toast(text: error.e)
                }
                
            case .success(let json):
                
                NotificationCenter.default.post(name: Notification.Name.sort_my_peculiarity, object: nil)
                
                self?.goback_previous_controller(animated: false) {
                    
                    let vc = ST_ExchangeByIncomeSuccessController()
                    
                    vc.overCurrentContext = true
                    
                    vc.json = json["data"]
                    
                    GlobalPresent(toController: vc)
                }
            }
            
        }).disposed(by: disposeBag)
    }
    
    fileprivate func render_step_view_from(step:Int){
        
        for (idx,item) in step_views.enumerated() {
            item.isHighlight.accept( idx < step )
        }
        
        for (idx,item) in step_line_views.enumerated() {
            item.isHighlight.accept( idx < step - 1 )
        }
        
    }
    
    
    fileprivate func status_updated(){
        
        guard let value = status_observable.value else {
            return
        }
        
        switch value{
        case .finished:
            
            confirm_btn.loading(status: false)
            render_step_view_from(step: 4)
            confirm_btn.setTitle("确认兑换", for: UIControl.State.normal)
            
        case .ongoing(let step,_):
            
            confirm_btn.loading(status: false)
            render_step_view_from(step: step)
            
//            render_step_view_from(step: Int.random(in: 1...4))
            
            confirm_btn.setTitle("立即进行提现认证", for: UIControl.State.normal)
            
        case .error(let error):
            confirm_btn.loading()
            self.toast(text: error.e)
        }
    }
    
    fileprivate func push_detect_face(){
        
        ToastDetectFaceTips(vcCreater: nil)
        
    }
    
    
    /*
    fileprivate func request_data(){
        
        JVrequest(PH.myAliAccountApi, success: { (json) in
            
            self.pd_Name = json["data"]["name"].stringValue
            
            self.accountLabel.text = json["data"]["title"].stringValue
            
            if let str = json["data"]["value"].string, str.count > 1{
                self.accountValueBtn.setTitle(str, for: UIControl.State.selected)
                self.accountValueBtn.isSelected = true
                self.accountValueBtn.isUserInteractionEnabled = false
                self.confirm_btn.isSelected = true
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
    }
     */
    
//    MARK: - Properties
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.backgroundColor = UIColor.white
        control.cornerRadius = 15
        return control
    }()
    
    fileprivate lazy var close_view:UIControl = {
       let control = UIControl()
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var left_label:UILabel = {
        let control = UILabel.init()
        control.text = "兑换"
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var goods_label:UILabel = {
        let control = UILabel.init()
        control.text = "兑换物品"
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var goods_name_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#FEC207")
        control.font = UIFont.systemFont(ofSize: 25, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var cash_subscribe_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
    
    
    fileprivate lazy var confirm_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
//        control.setTitle("\(Defaults[.PandaStr])兑换", for: UIControl.State.normal)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        control.cornerRadius = 22
        return control
    }()
    
    fileprivate lazy var step_views = [stepView1,stepView2,stepView3,stepView4]
    
    fileprivate lazy var step_line_views = [stepLine1,stepLine2,stepLine3]
    
    fileprivate lazy var stepView1:ST_ExchangeBindStepItemView = {
        let l = ST_ExchangeBindStepItemView(number: 1, title: "实名认证")
        return l
    }()
    
    fileprivate lazy var stepLine1:ST_ExchangeBindStepItemLine = {
        let l = ST_ExchangeBindStepItemLine()
        return l
    }()
    
    fileprivate lazy var stepView2:ST_ExchangeBindStepItemView = {
        let l = ST_ExchangeBindStepItemView(number: 2, title: "签订安全协议")
        return l
    }()
    
    fileprivate lazy var stepLine2:ST_ExchangeBindStepItemLine = {
        let l = ST_ExchangeBindStepItemLine()
        return l
    }()
    
    fileprivate lazy var stepView3:ST_ExchangeBindStepItemView = {
        let l = ST_ExchangeBindStepItemView(number: 3, title: "实名认证")
        return l
    }()
    
    fileprivate lazy var stepLine3:ST_ExchangeBindStepItemLine = {
        let l = ST_ExchangeBindStepItemLine()
        return l
    }()
    
    fileprivate lazy var stepView4:ST_ExchangeBindStepItemView = {
        let l = ST_ExchangeBindStepItemView(number: 4, title: "提现认证成功")
        return l
    }()

    //    MARK: - data
    var pd_Name = ""
    
    
    
    func create_cash_label_value(value:Double)  {
                
        let str = "当前积分：：".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
        
        str.append(String(format: "%.2f 积分", value).withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!)]))
        
        cash_subscribe_label.attributedText = str
         
    }
    
}

//MARK: - Event
extension ST_ConversionConfirmViewController{
    
    @objc fileprivate func close_handle(){
        goback_previous_controller()
    }
    
    /// 绑定支付宝 弃用
    @objc fileprivate func account_switch_handle(){
        
        /*
        if self.accountValueBtn.isSelected{
            return
        }
        
        let vc = ST_ConversionInputViewController()
        
        vc.pd_Name = pd_Name
        
        
        vc.append_closure = {[weak self] str in
            
            self?.accountValueBtn.setTitle(str, for: UIControl.State.selected)
            self?.accountValueBtn.isSelected = true
            self?.accountValueBtn.isUserInteractionEnabled = false
            self?.confirm_btn.isSelected = true
        }
        
        self.navigationController?.pushViewController(vc)
        */
    }
    
    
}


//MARK: -
fileprivate enum ZLBStatus {
    case ongoing(step:Int,link:URL)
    case finished
    case error(e:ST_NetworkError)
}

extension Result where Success == JSON,Failure == ST_NetworkError{
    
    fileprivate func covertToZLBStatus(step:Int)->ZLBStatus{
        
        switch self {
        case .success(let json1):
            if let url = json1["data"]["url"].url{
                return ZLBStatus.ongoing(step: step, link: url)
            }else{
                return ZLBStatus.error(e: ST_NetworkError(code: 0, e: "请稍后再试"))
            }
        case .failure(let err1):
            return ZLBStatus.error(e: err1)
        }
        
    }
}
